package org.geektimes.projects.user.service;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.repository.InMemoryUserRepository;
import org.geektimes.projects.user.sql.LocalTransactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.validation.Validator;

/**
 * 用户服务
 */
public class UserServiceImpl implements UserService {
    InMemoryUserRepository im = new InMemoryUserRepository();


    @Resource(name = "bean/EntityManager")
    private EntityManager entityManager;

    @Resource(name = "bean/Validator")
    private Validator validator;


    /**
     * 注册用户
     *
     * @param user 用户对象
     * @return 成功返回<code>true</code>
     */
    @Override
    @LocalTransactional
    public boolean register(User user) {
        entityManager.persist(user);

        // 调用其他方法方法
        update(user); // 涉及事务


//        boolean success = im.save(user);
//        if (success) {
//            return true;
//        }
        return false;
    }

    /**
     * 注销用户
     *
     * @param user 用户对象
     * @return 成功返回<code>true</code>
     */
    @Override
    public boolean deregister(User user) {
        User userAll = im.getByNameAndPassword(user.getName(), user.getPassword());
        boolean success = im.deleteById(userAll.getId());
        if (success) {
            return true;
        }
        return false;
    }

    /**
     * 更新用户信息
     *
     * @param user 用户对象
     * @return
     */
    @Override
    @LocalTransactional
    public boolean update(User user) {
        boolean success =im.update(user);
        if (success) {
            return true;
        }
        return false;
    }

    @Override
    public User queryUserById(Long id) {
        return null;
    }

    @Override
    public User queryUserByNameAndPassword(String name, String password) {
        return null;
    }
}
